package com.example.icampusevent;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.icampusevent.jsonobjects.FriendEvent;
import com.example.icampusevent.jsonobjects.ReturnStatus;
import com.google.gson.Gson;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class CheckinActivity extends Activity {

	private long eventId;
	private String userId; 
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkin);
        
        // Disable the built-in main action bar
        getActionBar().setDisplayShowHomeEnabled(false);
        getActionBar().setDisplayShowTitleEnabled(false);
        
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        
        Intent intent = getIntent();
        this.eventId= intent.getLongExtra("EVENTID", 0);
        this.userId = intent.getStringExtra("USERID");
        
        // Set up OnClickListener for buttons
        Button checkinButton = (Button)findViewById(R.id.checkin_button);
        checkinButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkin();
			}
        });
        
        Button inviteButton = (Button)findViewById(R.id.invite_button);
        inviteButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				inviteFriends();
			}
        });
    }
    
    
    @Override
    public void onResume() {
    	super.onResume();
    	
    	Intent intent = getIntent();
        this.eventId= intent.getLongExtra("EVENTID", 0);
        this.userId = intent.getStringExtra("USERID");
        
        NotCheckedinFriendListFragment fragment = (NotCheckedinFriendListFragment)(getFragmentManager().findFragmentByTag("invite_friends_fragment"));
        fragment.updateFriendList();
    }
    
    @Override
    public void onNewIntent(Intent newIntent) {
    	setIntent(newIntent);
    }
    
    
    private void checkin() {
    	String comment = ((EditText)findViewById(R.id.checkin_comment)).getText().toString();
    	comment = comment.replaceAll(" ", "+");
    	String url = "http://hamedaan.usc.edu:8080/team15/InviteServlet?q=checkin&eventid=" + eventId + 
    			"&userid=" + userId + "&comment=" + comment;
    	CheckinTask task = new CheckinTask();
    	task.execute(url);
    }
    
    
    private void inviteFriends() {
    	NotCheckedinFriendListFragment fragment = (NotCheckedinFriendListFragment)getFragmentManager()
    			.findFragmentByTag("invite_friends_fragment");
    	ArrayList<FriendEvent> selected = fragment.getSelectedFriends();
    	
    	String url = "http://hamedaan.usc.edu:8080/team15/InviteServlet?q=invite&eventid=" + eventId 
    			+ "&userid=" + userId;
    	for(FriendEvent friend : selected) {
    		url += "&friendid=" + friend.getUserid();
    	}
    	InviteFriendsTask task = new InviteFriendsTask();
    	task.execute(url);
    }
    
    
    private class InviteFriendsTask extends AsyncTask<String, Integer, Reader> {
	    protected Reader doInBackground(String... url) {
	    	InputStream source = retrieveStream(url[0]);
	 		if(source == null) return null;
	 		
	 		Reader inputReader = new InputStreamReader(source);
	 		return inputReader;
	    }

	    protected void onPostExecute(Reader json) {
	 		Gson gson = new Gson();
			ReturnStatus rStatus = gson.fromJson(json, ReturnStatus.class);
			if(rStatus.getStatus().equals("success")) {
				toast("Send Invitations Successfully!");
			}
			else {
				toast("Error!");
			}
	    }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		return null;
	 	}
	}
    
    
    private class CheckinTask extends AsyncTask<String, Integer, Reader> {
	    protected Reader doInBackground(String... url) {
	    	InputStream source = retrieveStream(url[0]);
	 		if(source == null) return null;
	 		
	 		Reader inputReader = new InputStreamReader(source);
	 		return inputReader;
	    }

	    protected void onPostExecute(Reader json) {
	 		Gson gson = new Gson();
			ReturnStatus rStatus = gson.fromJson(json, ReturnStatus.class);
			if(rStatus.getStatus().equals("success")) {
				toast("Check In Successfully!");
				
				// Navigate back to main activity
				Intent intent = new Intent(CheckinActivity.this, MainActivity.class);
				intent.putExtra("USERID", userId);
				startActivity(intent);
			}
			else {
				toast("Error!");
			}
	    }
	     
	    // Get data stream from server
	 	private InputStream retrieveStream(String url) {
	 		DefaultHttpClient client = new DefaultHttpClient();
	 		HttpGet request = new HttpGet(url);
	 		try {
	 			HttpResponse response = client.execute(request);
	 			final int status = response.getStatusLine().getStatusCode();
	 			if(status != HttpStatus.SC_OK) {
	 				toast("ERROR CODE: " + status + " for URL " + url);
	 				return null;
	 			}
	 			HttpEntity responseEntity = response.getEntity();
	 			return responseEntity.getContent();
	 		}
	 		catch(IOException e) {
	 			request.abort();
	 			toast("ERROR for " + url);
	 		}
	 		return null;
	 	}
	}
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_checkin, menu);
        return true;
    }
    
    
    public String getUserId() {
    	return this.userId;
    }
    
    public long getEventId() {
    	return this.eventId;
    }
    
    public void toast(String s) {
		CharSequence text = s;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(this, text, duration);
		toast.show();
	}
    
}
